<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import { ElDialog, ElButton, ElInput, ElTable, ElTableColumn, ElCheckbox, ElMessage } from 'element-plus';
import 'element-plus/dist/index.css';
// Declare vscode API for TypeScript
declare global {
  interface Window {
    vscode: {
      postMessage: (message: any) => void;
    };
  }
}

// Define message interfaces
interface FileItem {
  name: string;
  isDirectory: boolean;
  filePath: string;
}

interface FileListMessage {
  command: 'fileList';
  files: FileItem[];
  path: string;
  error?: string;
}

interface VSCodeMessage {
  command: string;
  [key: string]: any;
}

// 文件传输任务接口
interface FileTransferTask {
  id: string;
  fileName: string;
  devicePath: string;
  filePath: string; // 添加文件的绝对路径
}

interface Device {
  id: string;
  name: string;
}
const dialogTableVisible = ref(false);
const devicePathDialogVisible = ref(false);
const currentEditingTaskId = ref(''); // 当前正在编辑的任务ID

const selectedOptions = ref<string[]>([]);
const options = ref<Device[]>([]);

// Current directory path
const currentPath = ref('');
const devicePath = ref('');

// File list data
const fileList = ref<FileItem[]>([]);

// Selected files tracking
const selectedFiles = ref<string[]>([]);

// Loading state
const isLoading = ref(false);
const isDevicesLoading = ref(false);
const errorMessage = ref('');

// 文件传输任务列表
const transferTasks = ref<FileTransferTask[]>([]);

// 刷新设备列表
const refreshDevices = () => {
  isDevicesLoading.value = true;
  window.vscode.postMessage({
    command: 'getDevices'
  });
};

// 删除任务
const removeTask = (taskId: string) => {
  const index = transferTasks.value.findIndex(task => task.id === taskId);
  if (index !== -1) {
    transferTasks.value.splice(index, 1);
    ElMessage({
      type: 'success',
      message: '已删除任务'
    });
  }
};

// 确认所有任务
const confirmAllTasks = () => {
  // 检查是否选择了设备
  if (selectedOptions.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请先选择设备'
    });
    return;
  }

  // 检查是否有任务
  if (transferTasks.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请先添加传输任务'
    });
    return;
  }

  // 检查每个任务是否都有设备路径
  const incompleteTask = transferTasks.value.find(task => !task.devicePath);
  if (incompleteTask) {
    ElMessage({
      type: 'warning',
      message: `文件 "${incompleteTask.fileName}" 未设置设备路径`
    });
    return;
  }

  // 创建一个可序列化的任务数据对象
  const serializableTasks = transferTasks.value.map(task => ({
    id: task.id,
    fileName: task.fileName,
    devicePath: task.devicePath,
    filePath: task.filePath
  }));

  // 将数据发送给插件端
  window.vscode.postMessage({
    command: 'confirmTasks',
    devices: [...selectedOptions.value], // 创建一个新数组避免引用问题
    tasks: serializableTasks
  });

  ElMessage({
    type: 'success',
    message: '已提交传输任务'
  });
};

// 处理设备目录变化
const changeDeviceDirectory = (deviceId: string, dir: string) => {
  // 清空选择
  selectedFiles.value = [];
  isLoading.value = true;
  errorMessage.value = '';
  
  // 计算新路径
  let newPath = '';
  if (dir === '..') {
    // 如果是上级目录，则获取当前路径的父目录
    newPath = devicePath.value.substring(0, devicePath.value.lastIndexOf('/')) || '/';
  } else {
    // 如果是子目录，则拼接路径
    newPath = (devicePath.value === '/' ? devicePath.value : devicePath.value + '/') + dir;
    newPath = newPath.replace(/\/\//g, '/'); // 替换可能的双斜杠
  }
  
  // 请求设备文件列表
  window.vscode.postMessage({
    command: 'getDeviceFiles',
    deviceId: deviceId,
    path: newPath
  });
};

// 处理设备文件行点击
const handleDeviceRowSingleClick = (file: FileItem) => {
  // 只有当点击的是目录时才进行导航
  if (file.isDirectory && currentEditingTaskId.value) {
    isLoading.value = true;
    const taskIndex = transferTasks.value.findIndex(task => task.id === currentEditingTaskId.value);
    if (taskIndex !== -1) {
      const deviceId = selectedOptions.value[0] as string;
      if (deviceId) {
        changeDeviceDirectory(deviceId, file.name);
      }
    }
  }
};

// 打开设备路径选择对话框
const openDevicePathDialog = (taskId: string) => {
  currentEditingTaskId.value = taskId;
  const task = transferTasks.value.find(t => t.id === taskId);
  if (task) {
    devicePath.value = task.devicePath || '';
  } else {
    devicePath.value = '';
  }
  devicePathDialogVisible.value = true;
  
  // 请求设备文件列表
  isLoading.value = true;
  errorMessage.value = '';
  
  // 确保有选中的设备
  if (selectedOptions.value.length > 0) {
    window.vscode.postMessage({
      command: 'getDeviceFiles',
      deviceId: selectedOptions.value[0],
      path: devicePath.value // 传入当前路径，如果为空，后端会使用缓存的路径
    });
  } else {
    errorMessage.value = '请先选择一个设备';
    isLoading.value = false;
  }
};

// 确认设备路径选择
const confirmDevicePath = () => {
  if (currentEditingTaskId.value) {
    const index = transferTasks.value.findIndex(task => task.id === currentEditingTaskId.value);
    if (index !== -1) {
      transferTasks.value[index].devicePath = devicePath.value;
      ElMessage({
        type: 'success',
        message: '已更新设备路径'
      });
    }
  }
  devicePathDialogVisible.value = false;
};

// Toggle file selection
const toggleSelection = (fileName: string) => {
  if (selectedFiles.value.includes(fileName)) {
    selectedFiles.value = selectedFiles.value.filter(name => name !== fileName);
  } else {
    selectedFiles.value.push(fileName);
  }
};

// Check if a file is selected
const isSelected = (fileName: string) => {
  return selectedFiles.value.includes(fileName);
};

// Search functionality
const searchText = ref('');
const filteredFiles = computed(() => {
  if (!searchText.value) return fileList.value;
  return fileList.value.filter(file => 
    file.name.toLowerCase().includes(searchText.value.toLowerCase())
  );
});

// Handle directory change
const changeDirectory = (dir: string) => {
  // Clear selections when changing directories
  selectedFiles.value = [];
  isLoading.value = true;
  errorMessage.value = '';
  
  // Calculate new path
  let newPath = dir === '..' 
    ? currentPath.value.substring(0, currentPath.value.lastIndexOf('/')) || '/'
    : `${currentPath.value}/${dir}`.replace(/\/\//g, '/');
  
  // Request files from extension
  window.vscode.postMessage({
    command: 'getFiles',
    path: newPath
  });
};

// Handle file/directory interaction
const handleRowClick = (file: FileItem) => {
  if (file.isDirectory) {
    changeDirectory(file.name);
  } else {
    toggleSelection(file.name);
  }
};

// Handle single click on row
const handleRowSingleClick = (file: FileItem, column: any) => {
  // 只有当点击的是目录并且不是复选框列时才进行导航
  if (file.isDirectory && column.label !== '') {
    isLoading.value = true;
    changeDirectory(file.name);
  }
};

// Confirm selection
const confirmSelection = () => {
  const selectedCount = selectedFiles.value.length;
  
  // 将选中的文件添加到传输任务列表
  selectedFiles.value.forEach(fileName => {
    // 生成唯一ID
    const newId = Date.now() + '-' + Math.random().toString(36).substr(2, 9);
    
    // 创建新任务项，并添加文件绝对路径
    const newTask: FileTransferTask = {
      id: newId,
      fileName: fileName,
      devicePath: '', // 设备路径默认为空
      filePath: `${currentPath.value}/${fileName}`.replace(/\/\//g, '/') // 保存完整文件路径
    };
    
    // 添加到任务列表
    transferTasks.value.push(newTask);
  });
  
  // 向插件发送选择的文件信息（保留原有功能）
  window.vscode.postMessage({
    command: 'filesSelected',
    files: selectedFiles.value.map(name => {
      return {
        name: name,
        path: `${currentPath.value}/${name}`.replace(/\/\//g, '/')
      };
    })
  });
  
  // 关闭对话框并清空选择
  dialogTableVisible.value = false;
  
  // 显示成功消息
  if (selectedCount > 0) {
    ElMessage({
      type: 'success',
      message: `已添加 ${selectedCount} 个文件到任务列表`
    });
  }
  
  // 清空选择的文件
  selectedFiles.value = [];
};

// Setup communication with VSCode extension
onMounted(() => {
  // 在组件加载时立即请求设备列表
  window.vscode.postMessage({
    command: 'getDevices'
  });

  // Request initial file list when dialog is opened
  watch(dialogTableVisible, (newVal) => {
    if (newVal) {
      isLoading.value = true;
      errorMessage.value = '';
      window.vscode.postMessage({
        command: 'getFiles',
        path: ''  // 不指定路径，让插件使用默认路径
      });
    }
  });

  // Listen for messages from the extension
  window.addEventListener('message', (event: MessageEvent<VSCodeMessage>) => {
    const message = event.data;
    
    switch (message.command) {
      case 'fileList':
        isLoading.value = false;
        const fileListMsg = message as FileListMessage;
        
        if (fileListMsg.error) {
          errorMessage.value = fileListMsg.error;
          console.error('Error loading files:', fileListMsg.error);
        } else {
          fileList.value = fileListMsg.files || [];
          currentPath.value = fileListMsg.path || '/';
        }
        break;
        
      case 'deviceFileList':
        isLoading.value = false;
        
        if (message.error) {
          errorMessage.value = message.error;
          console.error('Error loading device files:', message.error);
        } else {
          fileList.value = message.files || [];
          devicePath.value = message.path || '/sdcard';
        }
        break;
        
      case 'devicesDetected':
        // 处理设备列表数据
        isDevicesLoading.value = false;
        if (message.devices && Array.isArray(message.devices)) {
          options.value = message.devices;
          console.log('Devices loaded:', options.value);
        } else {
          console.error('Invalid devices data received', message);
        }
        break;
        
      case 'tasksProcessed':
        // 处理任务处理结果
        if (message.success) {
          ElMessage({
            type: 'success',
            message: 'success'
          });
        } else {
          ElMessage({
            type: 'error',
            message: message.error || 'error'
          });
        }
        break;
        
      // Handle other messages from extension
    }
  });
});
</script>

<template>
  <div class="main-container dark">
    <!-- Page header -->
    <div class="main-font">一键推包</div>
    
    <div class="select-container">
      <div class="second-font">选择设备</div>
      <div class="device-select-header">
        <el-select
          v-model="selectedOptions"
          multiple
          collapse-tags
          collapse-tags-tooltip
          placeholder="请选择设备"
          style="width: calc(100% - 62px)"
          :loading="isDevicesLoading"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-button type="primary" size="small" @click="refreshDevices" :loading="isDevicesLoading">刷新</el-button>
      </div>
    </div>

    <!-- 文件传输任务表格 -->
    <div class="task-table-container">
      <div class="task-table-header">
        <div class="second-font">设备列表</div>
        <el-button type="primary" size="small" @click="dialogTableVisible = true">新增</el-button>
      </div>
      <el-table :data="transferTasks" style="width: 100%">
        <el-table-column label="文件">
          <template #default="scope">
            <el-tooltip 
              effect="dark" 
              :content="scope.row.filePath || scope.row.fileName" 
              placement="top-start"
              :show-after="500"
            >
              <span>{{ scope.row.fileName }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="设备路径" >
          <template #default="scope">
            <a 
              href="javascript:void(0)" 
              class="device-path-link"
              @click="openDevicePathDialog(scope.row.id)"
            >
              {{ scope.row.devicePath || '点击选择设备路径' }}
            </a>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              @click="removeTask(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="task-table-footer">
        <el-button type="primary" @click="confirmAllTasks">确认</el-button>
      </div>
    </div>

    <!-- 文件选择对话框 -->
    <el-dialog v-model="dialogTableVisible" title="文件选择" width="800">
      <div class="file-explorer">
        <div class="current-path">
          <span>Current path: {{ currentPath }}</span>
        </div>
        
        <div class="search-container">
          <el-input
            v-model="searchText"
            placeholder="Search files..."
            clearable
          />
        </div>
        
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        
        <div v-else-if="isLoading" class="loading-container">
          Loading files...
        </div>
        
        <div v-else class="file-list-container">
          <el-table 
            :data="filteredFiles" 
            style="width: 100%"
            @row-dblclick="handleRowClick"
            @row-click="handleRowSingleClick"
          >
            <el-table-column width="50">
              <template #default="scope">
                <span v-if="scope.row.isDirectory" data-is-directory="true">📁</span>
                <span v-else>📄</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="name" label="Name">
              <template #default="scope">
                <span 
                  :class="{ 'directory-name': scope.row.isDirectory }" 
                  :data-is-directory="scope.row.isDirectory"
                >
                  {{ scope.row.name }}
                </span>
              </template>
            </el-table-column>
            
            <el-table-column width="70" align="center">
              <template #default="scope">
                <el-checkbox 
                  v-if="!scope.row.isDirectory"
                  :model-value="isSelected(scope.row.name)"
                  @change="toggleSelection(scope.row.name)"
                  @click.stop
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="selection-summary" v-if="selectedFiles.length > 0">
          已选项: {{ selectedFiles.length }}
        </div>
        
        <div class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection" :disabled="selectedFiles.length === 0">
            确认 ({{ selectedFiles.length }})
          </el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 设备路径选择对话框 -->
    <el-dialog v-model="devicePathDialogVisible" title="选择设备路径" width="800">
      <div class="file-explorer">
        <div class="current-path">
          <span>设备路径: {{ devicePath }}</span>
        </div>
        
        <div class="search-container">
          <el-input
            v-model="searchText"
            placeholder="选择文件..."
            clearable
          />
        </div>
        
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        
        <div v-else-if="isLoading" class="loading-container">
          Loading files...
        </div>
        
        <div v-else class="file-list-container">
          <el-table 
            :data="filteredFiles" 
            style="width: 100%"
            @row-click="handleDeviceRowSingleClick"
          >
            <el-table-column width="50">
              <template #default="scope">
                <span v-if="scope.row.isDirectory" data-is-directory="true">📁</span>
                <span v-else>📄</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="name" label="Name">
              <template #default="scope">
                <span 
                  :class="{ 'directory-name': scope.row.isDirectory }" 
                  :data-is-directory="scope.row.isDirectory"
                >
                  {{ scope.row.name }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="dialog-footer">
          <el-button @click="devicePathDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDevicePath">
            确认选择 {{ devicePath }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>  
</template>

<style scoped>
.main-container{
  margin: 0 auto;
  padding: 20px;
  width: 100%;
  height: 100vh;
}
.file-explorer {
  display: flex;
  flex-direction: column;
  height: 400px;
}
.main-font{
  font-size: 18px;
}
.second-font{
  font-size: 16px;
}
.current-path {
  margin-bottom: 10px;
  padding: 5px;
  background-color: #2B2B2C;
  border-radius: 4px;
}

.search-container {
  margin-bottom: 15px;
}

.file-list-container {
  flex: 1;
  overflow: auto;
  border: 1px solid #636466;
  border-radius: 4px;
}

/* 自定义表格行样式 */
:deep(.el-table__row) {
  cursor: default;
}

:deep(.el-table__row:has([data-is-directory="true"])) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-table__row:has([data-is-directory="true"]):hover) {
  background-color: #ecf5ff;
}

.loading-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.error-message {
  flex: 1;
  padding: 20px;
  color: #f56c6c;
  background-color: #fef0f0;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.selection-summary {
  margin-top: 10px;
  font-size: 0.9em;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
  gap: 10px;
}

.directory-name {
  color: #409eff;
  font-weight: 500;
}
.select-container {
  margin: 20px 0;
  border-radius: 4px;
  padding: 15px;
  background-color: #141414;
}

/* 任务表格样式 */
.task-table-container {
  margin: 20px 0;
  border-radius: 4px;
  padding: 15px;
  background-color: #141414;
}

.task-table-container h2 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
  color: #A3A6AD;
}

.task-table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.task-table-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

/* 设备路径链接样式 */
.device-path-link {
  color: #409eff;
  text-decoration: none;
  cursor: pointer;
}

.device-path-link:hover {
  text-decoration: underline;
}

.device-path-link:empty::after {
  content: '点击选择设备路径';
  color: #909399;
  font-style: italic;
}

.device-select-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  margin: 20px 0 10px 0;
}
</style>